package com.huika.dealontop.control.myinfo.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.Response;
import com.google.gson.reflect.TypeToken;
import com.huika.dealontop.GlobalApp;
import com.huika.dealontop.R;
import com.huika.dealontop.config.UrlConstants;
import com.huika.dealontop.control.base.BaseAct;
import com.huika.dealontop.control.base.BaseFra;
import com.huika.dealontop.control.login.activity.LoginActivity;
import com.huika.dealontop.control.myinfo.activity.FeedbackActivity;
import com.huika.dealontop.control.myinfo.activity.MemberInfoDetailActivity;
import com.huika.dealontop.control.myinfo.activity.MyCouponActivity;
import com.huika.dealontop.control.myinfo.activity.MyEvaluateActivity;
import com.huika.dealontop.control.myinfo.activity.MyOrderListActivity;
import com.huika.dealontop.control.myinfo.activity.SettingActivity;
import com.huika.dealontop.support.domain.UserInfoDetailBean;
import com.huika.dealontop.support.domain.UserModel;
import com.huika.dealontop.support.http.FormResultRequest;
import com.huika.dealontop.support.http.JSONWrapAjaxParams;
import com.huika.dealontop.support.http.RequestResult;
import com.huika.dealontop.utils.GMapUtil;
import com.huika.dealontop.utils.LoginUtils;
import com.huika.dealontop.utils.PreferencesHelper;
import com.huika.dealontop.views.RoundImageView;
import com.huika.dealontop.views.webview.BaseWebViewAct;
import com.huika.huikalib.utils.StringUtils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

public class MyInfoFragment extends BaseFra implements GMapUtil.MyLocationCityListener {
    private RoundImageView myinfo_user_headimg;
    private TextView tv_myinfo_user_account, tv_myinfo_user_address, tv_myinfo_all_order_num,
            tv_myinfo_daifukuan_num, tv_myinfo_daishiyong_num, tv_myinfo_all_pingjia_num,
            tv_myinfo_all_pingjia_quannum, myinfo_da_num;
    private LinearLayout ll_myinfo_lin_all_order, ll_myinfo_order_daifukuan, ll_myinfo_order_daishiyong,
            ll_myinfo_order_daipingjia, ll_myinfo_lin_all_pingjia, ll_myinfo_lin_all_quan, ll_myinfo_lin_fankui,
            ll_myinfo_lin_about;
    public DisplayImageOptions options;
    private ImageView iv_myinfo_login, myinfo_logininfo, iv_myinfo_setting;
    private BaseAct baseAct;
    private UserModel userBean;

    private String cityJson = "";
    private String city = "";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected View inflaterView(LayoutInflater inflater, ViewGroup container, Bundle bundle) {
        View root = inflater.inflate(R.layout.frag_myinfo, container, false);
        baseAct = (BaseAct) getActivity();
        return root;
    }

    @Override
    protected void initWidget(View parentView) {
        super.initWidget(parentView);
        new GMapUtil(getActivity(), this).getLatestGeoAddress();
        CommonCity();
        myinfo_user_headimg = (RoundImageView) parentView.findViewById(R.id.myinfo_user_headimg);
        tv_myinfo_user_account = (TextView) parentView.findViewById(R.id.myinfo_user_account);
        tv_myinfo_user_address = (TextView) parentView.findViewById(R.id.myinfo_user_address);
        tv_myinfo_all_order_num = (TextView) parentView.findViewById(R.id.myinfo_all_order_num);
        tv_myinfo_daifukuan_num = (TextView) parentView.findViewById(R.id.myinfo_daifukuan_num);
        tv_myinfo_daishiyong_num = (TextView) parentView.findViewById(R.id.myinfo_daishiyong_num);
        myinfo_da_num = (TextView) parentView.findViewById(R.id.myinfo_da_num);
        tv_myinfo_all_pingjia_num = (TextView) parentView.findViewById(R.id.myinfo_all_pingjia_num);
        tv_myinfo_all_pingjia_quannum = (TextView) parentView.findViewById(R.id.myinfo_all_pingjia_quannum);
        iv_myinfo_login = (ImageView) parentView.findViewById(R.id.myinfo_login);
        myinfo_logininfo = (ImageView) parentView.findViewById(R.id.myinfo_logininfo);

        ll_myinfo_lin_all_order = (LinearLayout) parentView.findViewById(R.id.myinfo_lin_all_order);
        ll_myinfo_order_daifukuan = (LinearLayout) parentView.findViewById(R.id.myinfo_order_daifukuan);
        ll_myinfo_order_daishiyong = (LinearLayout) parentView.findViewById(R.id.myinfo_order_daishiyong);
        ll_myinfo_order_daipingjia = (LinearLayout) parentView.findViewById(R.id.myinfo_order_daipingjia);
        ll_myinfo_lin_all_pingjia = (LinearLayout) parentView.findViewById(R.id.myinfo_lin_all_pingjia);
        ll_myinfo_lin_all_quan = (LinearLayout) parentView.findViewById(R.id.myinfo_lin_all_quan);
        ll_myinfo_lin_fankui = (LinearLayout) parentView.findViewById(R.id.myinfo_lin_fankui);
        ll_myinfo_lin_about = (LinearLayout) parentView.findViewById(R.id.myinfo_lin_about);
        iv_myinfo_setting = (ImageView) parentView.findViewById(R.id.myinfo_setting);
        InitListener();
        // 创建头像下载
        options = new DisplayImageOptions.Builder().showImageOnLoading(R.mipmap.my_infomation_user_icon)
                .showImageForEmptyUri(R.mipmap.my_infomation_user_icon)
                .showImageOnFail(R.mipmap.my_infomation_user_icon).cacheInMemory(true)// 开启内存缓存
                .cacheOnDisk(true) // 开启硬盘缓存
                .resetViewBeforeLoading(false).build();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (LoginUtils.isLogin()) {// 判断是否登录
            LoginUI();
            getUpdateUserDatas();
        } else {
            outLoginUI();
        }
    }

    //初始化监听控件方法
    private void InitListener() {
        tv_myinfo_user_account.setOnClickListener(this);
        myinfo_user_headimg.setOnClickListener(this);//头像
        ll_myinfo_lin_all_order.setOnClickListener(this);//我的订单
        ll_myinfo_order_daifukuan.setOnClickListener(this);//待付款
        ll_myinfo_order_daishiyong.setOnClickListener(this);//待使用
        ll_myinfo_order_daipingjia.setOnClickListener(this);//待评价
        ll_myinfo_lin_all_pingjia.setOnClickListener(this);//我的评价
        ll_myinfo_lin_all_quan.setOnClickListener(this);//我的优惠券
        ll_myinfo_lin_fankui.setOnClickListener(this);//意见反馈
        ll_myinfo_lin_about.setOnClickListener(this);//关于
        iv_myinfo_setting.setOnClickListener(this);//设置
        myinfo_logininfo.setOnClickListener(this);//进入个人资料页面
    }

    //未登录时UI处理方法
        private void outLoginUI() {
        myinfo_user_headimg.setImageResource(R.mipmap.my_infomation_user_icon);
        tv_myinfo_user_account.setText(Html.fromHtml("<u>" + getString(R.string.myinfo_user_account) + "</u>"));
        tv_myinfo_user_account.setTextSize(16);
        tv_myinfo_user_address.setVisibility(View.GONE);
        tv_myinfo_all_order_num.setVisibility(View.GONE);
        tv_myinfo_daifukuan_num.setVisibility(View.GONE);
        tv_myinfo_daishiyong_num.setVisibility(View.GONE);
        myinfo_da_num.setVisibility(View.GONE);
        tv_myinfo_all_pingjia_num.setVisibility(View.GONE);
        tv_myinfo_all_pingjia_quannum.setVisibility(View.GONE);
        iv_myinfo_login.setVisibility(View.GONE);
    }

    //登录后UI处理方法
    private void LoginUI() {
        userBean = GlobalApp.getInstance().getUserModel();
        if (userBean == null) {
            outLoginUI();
            return;
        }
        ImageLoader.getInstance().displayImage(userBean.getUserHeadImage(), myinfo_user_headimg, options);//设置用户头像
        if (!StringUtils.isEmpty(userBean.getNickName())) {
            tv_myinfo_user_account.setText(userBean.getNickName());
            tv_myinfo_user_account.setTextSize(14);
        }
        if (!StringUtils.isEmpty(city)) {
            tv_myinfo_user_address.setVisibility(View.VISIBLE);
            tv_myinfo_user_address.setText(getString(R.string.myinfo_user_address) + city.split(",")[0]);
        } else {
            tv_myinfo_user_address.setVisibility(View.GONE);

        }
        if (!userBean.getOrderQuantity().equals("0")) {
            tv_myinfo_all_order_num.setVisibility(View.VISIBLE);
            tv_myinfo_all_order_num.setText(userBean.getOrderQuantity() + "");
        } else {
            tv_myinfo_all_order_num.setVisibility(View.GONE);
        }
        if (!userBean.getPendingPayment().equals("0")) {
            tv_myinfo_daifukuan_num.setVisibility(View.VISIBLE);
            tv_myinfo_daifukuan_num.setText(userBean.getPendingPayment() + "");
            if (userBean.getPendingPayment().length() > 2) {
                tv_myinfo_daifukuan_num.setBackgroundResource(R.mipmap.circle2);
            } else {
                tv_myinfo_daifukuan_num.setBackgroundResource(R.mipmap.circle);
            }
        } else {
            tv_myinfo_daifukuan_num.setVisibility(View.GONE);
        }
        if (!userBean.getToBeUser().equals("0")) {
            tv_myinfo_daishiyong_num.setVisibility(View.VISIBLE);
            tv_myinfo_daishiyong_num.setText(userBean.getToBeUser() + "");
            if (userBean.getToBeUser().length() > 2) {
                tv_myinfo_daishiyong_num.setBackgroundResource(R.mipmap.circle2);
            } else {
                tv_myinfo_daishiyong_num.setBackgroundResource(R.mipmap.circle);
            }
        } else {
            tv_myinfo_daishiyong_num.setVisibility(View.GONE);
        }
        if (!userBean.getWaitComments().equals("0") || !"0".equals(userBean.getWaitComments())) {
            myinfo_da_num.setVisibility(View.VISIBLE);
            myinfo_da_num.setText(userBean.getWaitComments() + "");
            if (userBean.getWaitComments().length() > 2) {
                myinfo_da_num.setBackgroundResource(R.mipmap.circle2);
            } else {
                myinfo_da_num.setBackgroundResource(R.mipmap.circle);
            }
        } else {
            myinfo_da_num.setVisibility(View.GONE);
        }
        if (!userBean.getEvaluateQuantity().equals("0")) {
            tv_myinfo_all_pingjia_num.setVisibility(View.VISIBLE);
            tv_myinfo_all_pingjia_num.setText(userBean.getEvaluateQuantity() + "");
        } else {
            tv_myinfo_all_pingjia_num.setVisibility(View.GONE);
        }
        if (!userBean.getCouponQuantity().equals("0")) {
            tv_myinfo_all_pingjia_quannum.setVisibility(View.VISIBLE);
            tv_myinfo_all_pingjia_quannum.setText(userBean.getCouponQuantity() + "");
        }
        iv_myinfo_login.setVisibility(View.VISIBLE);
    }

    /***
     * 获取网络数据,刷新用户信息
     *
     * @author hh
     */
    public void getUpdateUserDatas() {
        executeUpdateUserInfoList();
    }

    /**
     * 获取网络数据,刷新用户信息
     */
    private void executeUpdateUserInfoList() {
        JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
        ajaxParams.putCommonTypeParam("userId", GlobalApp.getInstance().getUserModel().getUserID());
        FormResultRequest<UserInfoDetailBean> request = new FormResultRequest<UserInfoDetailBean>(UrlConstants
                .GETUSERINFO, getUserInfo, this, new TypeToken<RequestResult<UserInfoDetailBean>>() {
        }.getType());
        request.setRequestParams(ajaxParams);
        executeRequest(request);
    }

    private Response.Listener<RequestResult<UserInfoDetailBean>> getUserInfo = new Response
            .Listener<RequestResult<UserInfoDetailBean>>() {
        @Override
        public void onResponse(RequestResult<UserInfoDetailBean> result) {
            if (result.flag == 1) {
                if (result != null && result.getRs() != null) {
                    UserInfoDetailBean bean = result.getRs();
                    userBean.setOrderQuantity(bean.getOrderQuantity() + "");
                    userBean.setEvaluateQuantity(bean.getEvaluateQuantity() + "");
                    userBean.setCouponQuantity(bean.getCouponQuantity() + "");
                    userBean.setPendingPayment(bean.getPendingPayment() + "");
                    userBean.setToBeUser(bean.getToBeUser() + "");
                    userBean.setWaitComments(bean.getWaitComments() + "");
                    userBean.setPhone(bean.getPhone());
                    userBean.setEmail(bean.getEmail());
                    userBean.setReferralCode(String.valueOf(bean.getReferralCode()));
                    userBean.setNickName(bean.getNickName());
                    userBean.setUserHeadImage(bean.getUserHeadImage());
                    LoginUI();
                }
            }
            dismissLoadingDialog();
        }
    };

    @Override
    protected void widgetClick(View v) {

        super.widgetClick(v);
        switch (v.getId()) {
            case R.id.myinfo_user_headimg://进入个人资料页面
            case R.id.myinfo_user_account:
                if (LoginUtils.isLogin()) {
                    Intent intent = new Intent(getActivity(), MemberInfoDetailActivity.class);
                    intent.putExtra(MemberInfoDetailActivity.USER_ID, String.valueOf(GlobalApp.getInstance()
                            .getUserId()));
                    showActivity(getActivity(), intent);
                } else {
                    showActivity(getActivity(), LoginActivity.class);
                }
                break;
            case R.id.myinfo_logininfo:
                if (LoginUtils.isLogin()) {
                    Intent intent = new Intent(getActivity(), MemberInfoDetailActivity.class);
                    intent.putExtra(MemberInfoDetailActivity.USER_ID, String.valueOf(GlobalApp.getInstance()
                            .getUserId()));
                    showActivity(getActivity(), intent);
                } else {
                    showActivity(getActivity(), LoginActivity.class);
                }
                break;
            case R.id.myinfo_lin_all_order://进入我的订单页面
                if (LoginUtils.isLogin()) {
                    Intent intent = new Intent(getActivity(), MyOrderListActivity.class);
                    intent.putExtra(MyOrderListActivity.CONTENTKEY, 0);
                    showActivity(getActivity(), intent);
                } else {
                    showActivity(getActivity(), LoginActivity.class);
                }
                break;
            case R.id.myinfo_order_daifukuan://进入待付款页面
                if (LoginUtils.isLogin()) {
                    Intent intent = new Intent(getActivity(), MyOrderListActivity.class);
                    intent.putExtra(MyOrderListActivity.CONTENTKEY, 1);
                    showActivity(getActivity(), intent);
                } else {
                    showActivity(getActivity(), LoginActivity.class);
                }

                break;
            case R.id.myinfo_order_daishiyong://进入待使用页面
                if (LoginUtils.isLogin()) {
                    Intent intent = new Intent(getActivity(), MyOrderListActivity.class);
                    intent.putExtra(MyOrderListActivity.CONTENTKEY, 2);
                    showActivity(getActivity(), intent);
                } else {
                    showActivity(getActivity(), LoginActivity.class);
                }

                break;
            case R.id.myinfo_order_daipingjia://进入待评价页面
                if (LoginUtils.isLogin()) {
                    Intent intent = new Intent(getActivity(), MyOrderListActivity.class);
                    intent.putExtra(MyOrderListActivity.CONTENTKEY, 3);
                    showActivity(getActivity(), intent);
                } else {
                    showActivity(getActivity(), LoginActivity.class);
                }

                break;
            case R.id.myinfo_lin_all_pingjia://进入我的评价页面
//                VersionManager versionManager = new VersionManager(getActivity());
//                versionManager.checkVersion(false, true, new Handler());
                if (LoginUtils.isLogin()) {
                    showActivity(baseAct, MyEvaluateActivity.class);
                } else {
                    showActivity(getActivity(), LoginActivity.class);
                }
                break;
            case R.id.myinfo_lin_all_quan://进入我的优惠券页面
                if (LoginUtils.isLogin()) {
                    showActivity(getActivity(), MyCouponActivity.class);
                } else {
                    showActivity(getActivity(), LoginActivity.class);
                }
                break;
            case R.id.myinfo_lin_fankui://进入意见反馈页面
                if (LoginUtils.isLogin()) {
                    showActivity(getActivity(), FeedbackActivity.class);
                } else {
                    showActivity(getActivity(), LoginActivity.class);
                }

                break;
            case R.id.myinfo_lin_about://进入关于页面
                Intent aboutIntent = new Intent(baseAct, BaseWebViewAct.class);
                if ("1".equals(getString(R.string.common_lang))) {//中
                    aboutIntent.putExtra(BaseWebViewAct.PAGE_URL, "http://192.168.18.83:9090/html5/about_cn/about" +
                            ".html");
                } else if ("2".equals(getString(R.string.common_lang))) {//英
                    aboutIntent.putExtra(BaseWebViewAct.PAGE_URL, "http://192.168.18.83:9090/html5/about_en/about" +
                            ".html");
                } else {//泰
                    aboutIntent.putExtra(BaseWebViewAct.PAGE_URL, "http://192.168.18.83:9090/html5/about_th/about" +
                            ".html");
                }
                showActivity(baseAct, aboutIntent);
                break;
            case R.id.myinfo_setting://进入设置页面
                showActivity(getActivity(), SettingActivity.class);
                break;
        }
    }

    @Override
    public void getLatestCityAddress(String latestCityAddress) {
        if (StringUtils.isEmpty(latestCityAddress)) {
            return;
        }
        if (StringUtils.isEmpty(cityJson)) {
            city = latestCityAddress + ",1";
            cityJson = city;
            PreferencesHelper.getInstance().setString("cityJson", city);
            CommonCity();
            return;
        }
        if (!cityJson.contains(latestCityAddress)) {
            cityJson = latestCityAddress + ",1,," + cityJson;
            PreferencesHelper.getInstance().setString("cityJson", cityJson);
            CommonCity();
            return;
        }
        String[] arycitys = cityJson.split(",,");
        for (int i = 0; i < arycitys.length; i++) {
            if (arycitys[i].split(",")[0].equals(latestCityAddress)) {
                latestCityAddress = latestCityAddress + "," + (Integer.parseInt(arycitys[i].split(",")[1]) + 1);
            }
        }
        StringBuffer sb = new StringBuffer();
        sb.append(latestCityAddress);
        for (int i = 0; i < arycitys.length; i++) {
            if (!latestCityAddress.split(",")[0].equals(arycitys[i].split(",")[0])) {
                sb.append(",," + arycitys[i]);
            }
        }
        cityJson = sb.toString();
        PreferencesHelper.getInstance().setString("cityJson", cityJson);
        CommonCity();
    }

    private void CommonCity() {
        cityJson = PreferencesHelper.getString("cityJson");
        Log.d("TAG", "=====城市====================" + cityJson);
        if (!StringUtils.isEmpty(cityJson)) {
            String[] arycity = cityJson.split(",,");
            city = arycity[0];
            for (int i = 0; i < arycity.length; i++) {
                if (Integer.parseInt(city.split(",")[1]) < Integer.parseInt(arycity[i].split(",")[1])) {
                    city = arycity[i];
                }
            }
        }
    }

}
